package cn.school.controller.educational;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.school.common.api.CommonPage;
import cn.school.common.api.CommonResult;
import cn.school.common.exception.ApiException;
import cn.school.common.utils.StringUtils;
import cn.school.common.utils.SysUserUtils;
import cn.school.educational.entity.Subject;
import cn.school.educational.service.SubjectService;
import cn.school.educational.vo.SubjectExcelVo;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

import static cn.hutool.db.DbUtil.close;

@RestController
@Api(tags = "Subject => 科目管理")
@RequestMapping("/educational/subject")
public class SubjectController {
    @Autowired
    private SubjectService subjectService;


    @GetMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) throws IOException {
        EasyExcel.write(response.getOutputStream(), SubjectExcelVo.class).head(getHeader()).sheet("科目表").doWrite(null);
    }

    @PostMapping("/importData")
    public CommonResult<String> importSubjectExcel(@RequestParam("file") MultipartFile multipartFile){
        try {
            return subjectService.importSubjectExcel(multipartFile.getInputStream());
        } catch (ApiException apiException) {
            throw apiException;
        } catch (Exception e) {
            throw new ApiException("导入科目失败，请联系管理员");
        }
    }

    private List<List<String>> getHeader() {
        String first = "科目导入";
        List<List<String>> list = new ArrayList<List<String>>();
        List<String> head0 = new ArrayList<String>();
        head0.add(first);
        head0.add("科目编号");
        List<String> head1 = new ArrayList<String>();
        head1.add(first);
        head1.add("科目名称");
        list.add(head0);
        list.add(head1);
        return list;
    }

    @ApiOperation("获取列表")
    @GetMapping("/list")
    public CommonResult<CommonPage<Subject>> list(@RequestParam Map<String, Object> para) {
        int pageNum = Integer.parseInt((String) para.get("pageNum"));
        int pageSize = Integer.parseInt((String) para.get("pageSize"));
        Page<Subject> page = new Page<>();
        page.setSize(pageSize);
        page.setCurrent(pageNum);
        String beginTime = String.valueOf(para.get("beginTime"));
        String endTime = String.valueOf(para.get("endTime"));
        LambdaQueryWrapper<Subject> queryWrapper = new LambdaQueryWrapper<>();
        if(!org.springframework.util.StringUtils.isEmpty(para.get("beginTime")) && !org.springframework.util.StringUtils.isEmpty(para.get("end"))){
            queryWrapper.ge(Subject::getCreateTime, DateUtil.parse(beginTime));
            queryWrapper.le(Subject::getCreateTime, DateUtil.parse(endTime));
        }
        //添加租户条件
        queryWrapper.eq(Subject::getTenantId,SysUserUtils.getSysUser().getTenantId());

        IPage<Subject> iPage = this.subjectService.page(page, queryWrapper);
        return CommonResult.success(CommonPage.restPage(iPage));
    }

    @ApiOperation("根据班级获取列表")
    @GetMapping("/listByClassId/{classid}")
    public CommonResult<List<Subject>> listByClassId(@PathVariable String classid) {
        Map<String,Object> map = new HashMap<>();
        map.put("classId",classid);
        List<Subject> list = subjectService.listByClassId(map);
        return CommonResult.success(list);
    }

    @ApiOperation("获取单个科目")
    @GetMapping("/info/{id}")
    public CommonResult<Subject> getInfoById(@PathVariable Long id) {
        Subject subject = this.subjectService.getById(id);
        return CommonResult.success(subject);
    }


    @ApiOperation("添加科目")
    @PostMapping("/add")
    public CommonResult<Subject> add(@RequestBody Subject subject) {
        String tenantId = SysUserUtils.getSysUser().getTenantId();
        LambdaQueryWrapper<Subject> subjectQueryWrapper = new LambdaQueryWrapper<>();
        if (StrUtil.isNotEmpty(subject.getSubjName())) {
            subjectQueryWrapper.eq(Subject::getSubjName, subject.getSubjName())
            .eq(Subject::getTenantId,tenantId);
            int count = this.subjectService.count(subjectQueryWrapper);
            if (count >= 1) {
                throw new ApiException("科目名称重复，请检查科目编号");
            }
        }
        subject.setCreateTime(Calendar.getInstance().getTime());
        subject.setModifyTime(Calendar.getInstance().getTime());
        subject.setCreateBy(SysUserUtils.getSysUser().getId());

        boolean isAddSuccess = this.subjectService.save(subject);
        if (isAddSuccess) {
            return CommonResult.success();
        } else {
            return CommonResult.failed();
        }
    }

    @ApiOperation("更新科目")
    @PutMapping("/update/{id}")
    public CommonResult<Subject> update(@PathVariable Long id, @RequestBody Subject subject) {
        LambdaQueryWrapper<Subject> subjectQueryWrapper = new LambdaQueryWrapper<>();
        subjectQueryWrapper.ne(Subject::getId, subject.getId());

        subject.setModifyTime(Calendar.getInstance().getTime());
        subject.setModifyBy(SysUserUtils.getSysUser().getId());

        if (StrUtil.isNotEmpty(subject.getSubjName())) {
            subjectQueryWrapper.eq(Subject::getSubjName, subject.getSubjName());
            int count = this.subjectService.count(subjectQueryWrapper);
            if (count >= 1) {
                throw new ApiException("科目名称重复，请检查科目编号");
            }
        }
        boolean isUpdateSuccess = this.subjectService.updateById(subject);
        if (isUpdateSuccess) {
            return CommonResult.success();
        } else {
            return CommonResult.failed();
        }
    }


    @ApiOperation("删除科目")
    @DeleteMapping("/deleteByIds/{ids}")
    public CommonResult<Subject> delete(@PathVariable Long[] ids) {
        List<Long> idList = Arrays.stream(ids).collect(Collectors.toList());
        boolean isDeleteSuccess = this.subjectService.removeByIds(idList);
        if (isDeleteSuccess) {
            return CommonResult.success();
        } else {
            return CommonResult.failed();
        }
    }

    @ApiOperation("获取科目列表")
    @GetMapping("/getSubjectList")
    public CommonResult<List<Subject>> getSubjectList() {
        LambdaQueryWrapper<Subject> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Subject::getTenantId, SysUserUtils.getSysUser().getTenantId());
        List<Subject> subjects = subjectService.getBaseMapper().selectList(wrapper);
        return CommonResult.success(subjects);
    }

}
